package com.rankeiot.core.excel;

import com.rankeiot.core.translator.Translator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.Row;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;

public class PoiBatchImporter<T> extends ExcelBatchImporter<T>{
    public PoiBatchImporter(InputStream in, Class<T> dataType) {
        super(in, dataType);
    }

    public PoiBatchImporter(InputStream in, Map<String, Translator> translators, Class<T> dataType) {
        super(in, translators, dataType);
    }
    public Workbook createWorkBook(InputStream in) throws IOException {
        return new HSSFWorkbook(in);
    }
    @Override
    protected void load(InputStream in, TypedRowHandler th) {
        try {
            Workbook workbook = createWorkBook(in);
            Sheet sheet = workbook.getSheetAt(0);
            int rowCount = sheet.getPhysicalNumberOfRows();

            for(int rowNum = 0; rowNum < rowCount; ++rowNum) {
                Row rowData = sheet.getRow(rowNum);
                if (rowData != null) {
                    DataRow dataRow = new DataRow();
                    dataRow.setRowNum(rowNum);
                    for(Cell cellData:rowData){
                        if (cellData != null) {
                            Hyperlink link = cellData.getHyperlink();
                            if (link != null) {
                                dataRow.putLink(cellData.getColumnIndex(), link.getAddress());
                            }

                            CellType cellType = cellData.getCellType();
                            Object cellValue = null;
                            switch (cellType) {
                                case STRING:
                                    cellValue = cellData.getStringCellValue();
                                    break;
                                case BOOLEAN:
                                    cellValue = cellData.getBooleanCellValue();
                                case BLANK:
                                case ERROR:
                                default:
                                    break;
                                case NUMERIC:
                                    if (DateUtil.isCellDateFormatted(cellData)) {
                                        Date date = cellData.getDateCellValue();
                                        cellValue = date;
                                    } else {
                                        cellValue = cellData.getNumericCellValue();
                                    }
                            }
                            dataRow.put(cellData.getColumnIndex(), cellValue);
                        }

                    }
                    th.accept(dataRow);
                }
            }

        } catch (IOException var16) {
            throw new RuntimeException(var16);
        }
    }

}
